/**
 * Created by HuangZhongwei on 2016/12/5.
 */
//*************************用户组*************************8
var addDivIndex = 0;
var signDivIndex = 0;
var operate = 0;
var uid = 0;
var account='';
var name = '';
var email='';
var telephone='';
var sdid =0;
var sid=111;
var data='';

//加载的时候运行
$(function(){
	
	//加载数据
	FindData();

	$('#usertable').on('click-row.bs.table', function (e, row, element){
        var locked = row["locked"];
        var valid = row["valid"];
        //alert(type);
        if (valid == '失效')
        {
            $('#unlockedUser').attr("disabled", true);
            $('#lockedUser').attr("disabled", true);
            $('#invalidUser').attr("disabled", true);
            $('#updateUser').attr("disabled", true);
            $('#resetPassword').attr("disabled", true);
        }else{
        	if(locked=='锁定'){
        		$('#lockedUser').attr("disabled", true);
        		$('#updateUser').attr("disabled", true);
        		$('#unlockedUser').attr("disabled", false);

        	}else{
           		$('#lockedUser').attr("disabled", false);
           		$('#updateUser').attr("disabled", false);
           		$('#unlockedUser').attr("disabled",true);
        	}
        	    
        		$('#invalidUser').attr("disabled", false);
        		$('#resetPassword').attr("disabled", false);
        }

    });
    //查询
    $("#search").click(function(){
        FindData();
    });

    //新增按钮事件
 	$('#addUser').click(function(){
        var url = 'UserEdit.html';
        $("#AddUserDiv").load(url,function(){
        operate = 1;
        sid=111;
        });
        addDivIndex = ShowLayer($("#AddUserDiv"),'新增用户','400px','400px');
        });

    //修改按钮事件
    $('#updateUser').click(function(){
        //收集参数
        var url = 'UserEdit.html';
        data = getSelectedRow();
        uid=data.id;
        account=data.account;
        name=data.name;
        email=data.email;
        telephone=data.telephone;
        $("#AddUserDiv").load(url,function(){
           $('#useraccount').val(account);
            $('#useremail').val(email);
            $("#usertelephone").val(telephone);
			$('#username').val(name);
            operate = 2;
            sid=100;
        });
        addDivIndex = ShowLayer($("#AddUserDiv"),'修改用户','400px','400px');
    });

    //重置按钮事件
 	$('#resetPassword').click(function(){
        data = getSelectedRow();
        uid=data.id;
        operate = 6;
        sid=111;
		CallSign(sid,SignCallBack);
        });


  	//锁定按钮事件
 		$("#lockedUser").click(function(){
 			data = getSelectedRow();
            uid=data.id;
 			sid=111;
 			operate=3;
 			CallSign(sid,SignCallBack);
 		});
 		
 		//解锁按钮事件
 		$("#unlockedUser").click(function(){
 			data = getSelectedRow();
            uid=data.id;
            sid=111;
 			operate=4;
 			CallSign(sid,SignCallBack);
 		});
 		
 		//失效按钮事件
 		$("#invalidUser").click(function(){
 			data = getSelectedRow();
            uid=data.id;
            sid=111;
 			operate=5;
 			CallSign(sid,SignCallBack);
 		});

});

//查找数据
function FindData() {
	 $('#unlockedUser').attr("disabled", true);
            $('#lockedUser').attr("disabled", true);
            $('#invalidUser').attr("disabled", true);
            $('#updateUser').attr("disabled", true);
            $('#resetPassword').attr("disabled", true);
    var account=$("#account").val();
   	var name=$("#name").val();
   	var valid=$("#valid option:selected").val();
  	var locked=$("#locked option:selected").val();
   	$.ajax({
   		url: serverPath+"users/find",
   		xhrFields:{ withCredentials:true},
   		data:{"account":account,"name":name,"valid":valid,"locked":locked},
   		dataType:"json",
   		success: function(result){
   		var data=result.data;
   		$("#usertable").bootstrapTable('load',data);
   		},
   		error:function(){
   			//alert(1111);
   		}
   		});
}

//function CallSign(sid){
//  var url = "Signature.html";
//  $("#SignDiv").load(url,function(){
//      SignLoad(sid,SignCallBack);
//  });
//  signDivIndex = ShowLayer($("#SignDiv"),'签名',"400px","410px");
//
//};

//弹出Div层
function ShowLayer(showDiv,title,width,height) {
    var divIndex = layer.open({
        //layer提供了5种层类型。可传入的值有：0（信息框，默认）；1（页面层）；2（iframe层）；3（加载层）；4（tips层）。
        // 若你采用layer.open({type: 1})方式调用，则type为必填项（信息框除外）
        type: 1,
        //动画
        anim: 0,
        //title ：String
        //title: ['文本', 'font-size:18px;']
        //title: false 不显示标题栏
        title: [title, 'font-size:18px;font-weight:bold;'],
        //是否固定弹出
        fix: false,
        //最大小化按钮
        maxmin: false,
        //控制点击弹层外区域关闭
        shadeClose: false,
        //窗口大小 area: ['400px', '500px'] or auto 自适应大小
        area: [width, height],
        //area: '350px',
        //iframe层的url
        //content: 'http://www.baidu.com',
        content: showDiv,
        //是否允许拉伸
        resize: false,
        //浏览器滚动条
        scrollbar: false,
        zIndex: layer.zIndex, //重点1
        end: function () {
           // layer.setTop(divIndex); //重点2
        }
    });
    return divIndex;
};

//获取表格的选中行
 function getSelectedRow() {
        var selects = $('#usertable').bootstrapTable('getSelections');
        return selects[0];//返回选中行所有数据
    }

//*************************新增 or 修改*************************
//获取当前输入
function GetUserNow(){
    account=$('#useraccount').val();
    email=$('#useremail').val();
    telephone=$("#usertelephone").val();
	name=$('#username').val();
}

//新增用户组方法
function AddUser(sdid){
    var url = serverPath+"users/add";
    var data = {"account":account,"name":name,"email":email,"telephone":telephone,"sdid":sdid};
    type="post";
    AddUpdateUser(url,data,type);
}

//修改用户组方法
function UpdateUser(sdid){
	var data ={"id":uid,"sdid":sdid,"account":account,"name":name,"email":email,"telephone":telephone};
    var url = serverPath+"users/update";
    type="put";
    AddUpdateUser(url,data,type);
}


//修改数据
function AddUpdateUser(url,data,type){

    $.ajax({
        url: url,
        data:data,
        xhrFields:{ withCredentials:true},
        type:type,
        dataType:"json",
        async: false,
        success: function(result){
            var errCode =  result.errorCode;
            var data=result.data;
            if(operate==1){
            	alert("新增用户密码为"+data.password)
            }
            ShowMsg('成功');
            AfterEdit();

        },
        error:function(){
        	ShowMsg('失败')
        	AfterEdit();
        }
    });
}

//锁定用户
	function LockedUser(sdid){
		$.ajax({
			url: serverPath+"users/locked",
			xhrFields:{ withCredentials:true},
			data:{"id":uid,"sdid":sdid},
			type:"put",
			dataType:"json",
			success: function(result){
				var errorCode=result.errorCode;
				if(errorCode==0){
					ShowMsg("成功");
					AfterEdit();
				}
			},
			error:function(){
				alert(1111);
			}

		});
	}
//解锁用户
	function UnlockedUser(sdid){
		$.ajax({
				  url: serverPath+"users/unlocked",
				  data:{"id":uid,"sdid":sdid},
				  type:"put",
				  xhrFields:{ withCredentials:true},
				  dataType:"json",
				  success: function(result){
					  var errorCode=result.errorCode;
					  if(errorCode==0){
						ShowMsg("成功");
						AfterEdit();
					  }
				  },
				  error:function(){
					  alert(1111);
				  }
				});
	}

//失效用户
	function InvalidUser(sdid){
		$.ajax({
				  url: serverPath+"users/invalid",
				  data:{"id":uid,"sdid":sdid},
				  xhrFields:{ withCredentials:true},
				  type:"put",
				  dataType:"json",
				  success: function(result){
					  var errorCode=result.errorCode;
					  if(errorCode==0){
						ShowMsg("成功");
						AfterEdit();
					  }

				  },
				  error:function(){
					  alert(1111);
				  }

				});
	}

//重置密码
	function ResetPassword(sdid){
		$.ajax({
				  url: serverPath+"login/resetPassword",
				  data:{"uid":uid,"sdid":sdid},
				  xhrFields:{ withCredentials:true},
				  type:"post",
				  dataType:"json",
				  success: function(result){
				  	var pwd=result.data;
					  var errorCode=result.errorCode;
					  if(errorCode==0){
						ShowMsg("成功");
						AfterEdit();
						alert(pwd);
					  }

				  },
				  error:function(){
					  alert(1111);
				  }

				});
	}


//提示信息  可以转移到父页面中弹出
    function ShowMsg(msg) {
        var msgInfo = '';
        if (operate == 1) {
            msgInfo = '新增' + msg + '！';
        } else if(operate == 2){
            msgInfo = '修改' + msg + '！';
        }else if(operate == 3){
        	msgInfo = '锁定' + msg + '！';
        }else if(operate==4){
        	msgInfo = '解锁' + msg + '！';
        }else if(operate==5){
        	msgInfo = '失效' + msg + '！';
        }else{
        	msgInfo = '重置' + msg + '！';
        }
        var index = layer.msg(msgInfo, {
                icon: 1, time: 1000 //1秒关闭（如果不配置，默认是3秒）
            },
            function () {
                if (msg == '成功') layer.close(addDivIndex);
            });
    }

function EditSave() {
    GetUserNow();
    //保存处理
    CallSign(sid,SignCallBack);
}

function EditCancel(){
    layer.close(addDivIndex);
}

//根据名称获取Url中某个参数的值
function GetUrlParam(pname){
    var reg = new RegExp("(^|&)" + pname + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if(r!=null) return decodeURI(r[2]);
    return null;
}
/**签名确认后的回调处理 真实的数据操作
 * @param sdid  签名返回的ID
 * @constructor
 */
    function SignCallBack(sdid){
        if (operate == 1) {
            AddUser(sdid);
        }
        if (operate == 2) {
            UpdateUser(sdid);
        }
        if (operate == 3) {
            LockedUser(sdid);
        }
        if (operate == 4){
        	UnlockedUser(sdid);
        }
        if (operate == 5){
        	InvalidUser(sdid);
        }
        if (operate == 6){
        	ResetPassword(sdid);
        }
    }


	
	//执行数据操作后执行的方法 如：关闭层、刷新
    function AfterEdit() {
        layer.close(signDivIndex);
        FindData();
    }

//字符串方法 format
String.prototype.format=function()
{
    if(arguments.length==0) return this;
    for(var s=this, i=0; i<arguments.length; i++)
        s=s.replace(new RegExp("\\{"+i+"\\}","g"), arguments[i]);
    return s;
};
